import  jwt from 'jsonwebtoken'
import { jwtSercert, expiresIn } from '../../config/index'
import Page from '../common/pageController'

const md5 = require('md5');
const ObjectId = require('mongoose').Types.ObjectId
const userModel  = require('../../mongodb/model/user.js')

const createToken = function(userInfo ) {
    const user = {
        userId : userInfo._id ,
        name : userInfo.name
    }
    return jwt.sign({
        ...user
    },  jwtSercert, { expiresIn })
}

const getUserInfoFromToken = function (ctx){
    return ctx.state.user
}

const commonResult = function(code, msg, data ){
    return {
        code : code || 0 ,
        msg  ,
        data ,
        serverTime : +new Date()
    }
}

const user = {
    // 注册新用户
    newUser: async (ctx, next) => {


        console.log(222)
        const register = ctx.request.body
        const md5password  = md5( register.password )
        let status = false
        let account = await userModel.find({
            name : register.userName
        })
        if( account.length ){
            ctx.send(commonResult(309, '账号已注册', null))
        }
        else{
            let res = await userModel.create({
                name : register.name ,
                password : md5password ,
                phone : register.phone
            })
            const token = createToken(res)
            ctx.send(commonResult(0, 'success', {token}))
        }
    },
    /*
    testSsr (ctx) {
        ctx.send(commonResult(0, 'success', {
            'a' : 1,
            'b' : 2,
            'c' : 3,
        }))
    },
    */
    // 登陆
    login: async (ctx, next) => {
        const userForm = ctx.request.body
        console.log( userForm )
        let res = await userModel.findOne({
            name : userForm.name ,
            //password: md5(userForm.password)
        }, {__v: 0})
        console.log(res)
        const type = userForm.loginType || 'password'
        const isMatch = type == 'password' ? (md5(userForm.password) === res.password)
            : ( userForm.record === res.HandLockPass )

        if(res){
            if( isMatch ){
                const token = createToken( res )
                ctx.send(commonResult(0, 'success', {token}))
            }else{
                ctx.send(commonResult(301, type == 'password' ? 'error 密码不正确' : 'error 手势不匹配', null))
            }
        }
        else{
            ctx.send(commonResult(309, '用户不存在，请先注册', null))
        }
    },
    async userInfo(ctx) {
        const userName  = ctx.state.user.name
        try{
            let res = await userModel.findOne({
                name: userName
            }, {__v: 0})
            const { headImgUrl, name } = res
            ctx.send( commonResult(0, 'success', {
                headImgUrl ,
                name
            }))
        }
        catch (err){
            throw err
        }
    },
    async updateHeadImg(ctx){
        const { name } = ctx.state.user
        const { url } = ctx.request.body
        try{
            let res = await userModel.update({
                name
            }, { headImgUrl: url })
            ctx.send( commonResult(0, 'success', null))
        }
        catch (err){
            throw err
        }
    },
    async handLockRecord (ctx){
        const { record } = ctx.request.body
        const { name } = ctx.state.user
        try {
            let res = await userModel.findOne({
                name : name
            }, {__v: 0})

            if(res){
                let recordRes = await userModel.update({
                    name
                }, {
                    HandLockPass: record
                })
                ctx.send( commonResult(0, 'success', null))
            }
            else{
                ctx.send(commonResult(309, '用户不存在，请先注册', null))
            }
        }catch (err) {
            throw  err
        }

    },
    async exist(ctx){
        const { userName } = ctx.query
        try{
            let res = await userModel.find({
                name: userName
            })
            if(res && res.length ){
                if( res[0].HandLockPass ){
                    ctx.send( commonResult(0, 'success', {
                        isExist : true ,
                        hasSetHandLock : true
                    }))
                }
                else{
                    ctx.send( commonResult(0, 'success', {
                        isExist : true ,
                        hasSetHandLock : false
                    }))
                }
            }
            else{
                ctx.send( commonResult(309, '请先注册', {
                    isExist : false
                }))
            }
        }
        catch (err){
            throw err
        }
    },

    async testNuxt (ctx) {
        try{
            ctx.send( commonResult(0, 'success', {
                isExist : true ,
                hasSetHandLock : false,
                userName : 'paul test Nuxt'
            }))
        }
        catch (err){
            throw err
        }
    }
}

export default user
